<template>
  <el-dialog
    v-model="visible"
    title="编辑库存项"
    width="1000"
    draggable
    :before-close="isClosed"
  >
    <el-form label-width="auto" :model="formData" ref="formRef" :inline="true">
      <!-- 库存名称 -->
      <el-form-item label="库存名称：" prop="productName" style="width: 46%">
        <el-input
          placeholder="请输入库存名称"
          v-model="formData.productName"
          maxlength="50"
        />
      </el-form-item>

      <!-- 品牌/款式 -->
      <el-form-item label="品牌/款式：" prop="brandOrStyle" style="width: 46%">
        <el-input
          placeholder="请输入品牌或款式"
          v-model="formData.brandOrStyle"
          maxlength="50"
        />
      </el-form-item>

      <!-- 规格型号 -->
      <el-form-item label="规格型号：" prop="specification" style="width: 46%">
        <el-input
          placeholder="请输入规格型号"
          v-model="formData.specification"
          maxlength="50"
        />
      </el-form-item>

      <!-- 内部牌号 -->
      <el-form-item label="内部牌号：" prop="internalBrand" style="width: 46%">
        <el-input
          placeholder="请输入内部牌号"
          v-model="formData.internalBrand"
          maxlength="50"
        />
      </el-form-item>

      <!-- 描述 -->
      <el-form-item label="备注：" prop="description" style="width: 96%">
        <el-input
          type="textarea"
          v-model="formData.description"
          :rows="2"
          placeholder="请输入补充说明"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isClosed">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
  
  <script lang="ts">
import { defineComponent, reactive, toRefs, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import request from "@/utils/request";

export default defineComponent({
  props: {
    editData: {
      type: Object,
      default: () => ({}),
    },
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    getList: {
      type: Function,
      default: () => () => {},
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      btnLoading: false,
      visible: false,
      formData: {
        productName: "",
        specification: "",
        type: null,
        stock: 0,
        brandOrStyle: "",
        internalBrand: "",
        isQuantityBased: null,
        unitPrice: 0,
        description: "",
        createdAt: "",
        updatedAt: "",
      },
    });

    const formRef = ref();

    // 关闭弹窗
    const isClosed = () => {
      state.visible = false;
      emit("update:dialogVisible", false); // 让父组件同步更新 `dialogVisible`
    };

    // 监听 props.dialogVisible 的变化
    watch(
      () => props.dialogVisible,
      (newVal) => {
        //console.log("dialogVisible 变化了:", newVal);
        state.visible = newVal;
        initData();
      }
    );

    // 初始化数据
    const initData = () => {
      //console.log("props.query:", props.editData);

      // 映射 type 和 quantityBased
      const typeMapping = {
        1: "原料",
        3: "其他",
        2: "成品",
      };

      const quantityMapping = {
        2: "只计重",
        1: "同时计件计重",
        0: "只计件",
      };

      const data = props.editData;

      state.formData = {
        ...state.formData,
        productName: data.productName || "",
        specification: data.specification || "",
        type: typeMapping[data.type] || "", // 显示文字
        stock: data.stock || 0,
        brandOrStyle: data.brandOrStyle || "",
        internalBrand: data.internalBrand || "",
        isQuantityBased: quantityMapping[data.isQuantityBased] || "", // 显示文字
        unitPrice: data.unitPrice || 0,
        description: data.description || "",
        createdAt: data.createdAt || "",
        updatedAt: data.updatedAt || new Date().toLocaleString(), // 覆盖 lastUpdated，使用当前时间
      };
    };

    // 提交表单
    const submit = async () => {
      state.btnLoading = true;
      const payload = {
        ...state.formData,
        // 将显示值转换为后端需要的数值格式
        type: convertTypeToNumber(state.formData.type),
        isQuantityBased: convertQuantityBasedToNumber(
          state.formData.isQuantityBased
        ),
        ...(props.editData.id && { id: props.editData.id }),
      };
      console.log(payload);

      try {
        const response = await request({
          method: "post",
          url: "inventory/products/editProduct",
          data: payload,
          headers: {
            "Content-Type": "application/json",
          },
        });
        if (response.data.success) {
          ElMessage.success("物料信息编辑成功");
          await props.getList();
          isClosed();
        }
      } catch (error) {
        console.log(error);
      } finally {
        state.btnLoading = false;
      }
    };

    // 类型转换函数
    const convertTypeToNumber = (typeText: string): number => {
      const mapping = {
        原料: 1,
        成品: 2,
        其他: 3,
      };
      return mapping[typeText] || 3;
    };

    const convertQuantityBasedToNumber = (quantityText: string): number => {
      const mapping = {
        同时计件计重: 1,
        只记件: 0,
        只记重: 2,
      };
      return mapping[quantityText] || 2;
    };

    return {
      ...toRefs(state),
      isClosed,
      formRef,
      submit,
    };
  },
});
</script>
  
<style scoped>
.layout {
  width: auto;
  height: 800px;
  background-color: #ffffff;
}
</style>
  